package wperror

import (
	"fmt"
	"runtime"

	//"wanyu/server/engine/wplog"
	log "gamesdk/wanyu/server/engine/wplog"
)

var serverID string

//New 创建一个业务错误
func New(err int32) error {
	return fmt.Errorf(`{"id":"%s","err": %d,"magicNum": -99	}`, serverID, err)
}

//NewError 错误码，带自定义错误信息输出
func NewError(err int32, describe string) error {
	return fmt.Errorf(`{"id":"%s","err": %d,"msg" : "%s","magicNum": -99	}`, serverID, err, describe)
}

//Catch 捕获错误
func Catch(err *error) {
	if ec := recover(); nil != ec {
		log.Error(ec)
		buf := make([]byte, 2048)
		length := runtime.Stack(buf, false)
		log.Error(string(buf[:length]))
		if nil != err {
			switch ec.(type) {
			case error:
				temp := ec.(error)
				*err = temp
			case string:
				temp := ec.(string)
				*err = fmt.Errorf(temp)
			default:
				log.Error("unkown type exception, ", ec)
			}
		}
	}
}

//check 检测是否产生了业务错误
func Check(cond bool, err int32, logargs ...interface{}) {
	if !cond {
		log.Error(logargs...)
		panic(New(err))
	}
}

//CheckError 检测错误
func CheckE(err error) {
	if nil != err {
		panic(err)
	}
}


//CheckEMultiParam 检查多返回值的情况，必须保证最后一个是error
func CheckEMultiParam(params ...interface{}) {
	if params[len(params)-1] != nil {
		panic(params[len(params)-1])
	}
}

//CheckError 检测错误
func CheckError(cond bool, err error) {
	if !cond {
		panic(err)
	}
}

//CheckErrorWithLog 检测错误并，并打印日志
func CheckErrorWithLog(err error, logstart string) {
	if err != nil {
		log.Error(logstart)
		panic(err)
	}
}

//SetServerID 设置服务编号
func SetServerID(id string) {
	serverID = id
}
